package gobase

import (
	"io"
	"sync"
)

type MultiWriter struct {
	lk   sync.RWMutex
	wlst []io.Writer
}

func NewMultiLogW() *MultiWriter {
	return &MultiWriter{}
}

func (this *MultiWriter) AddWriter(w io.Writer) {
	this.lk.Lock()
	defer this.lk.Unlock()
	for i := 0; i < len(this.wlst); i++ {
		if this.wlst[i] == w {
			return
		}
	}
	this.wlst = append(this.wlst, w)
}

func (this *MultiWriter) DelWriter(w io.Writer) {
	this.lk.Lock()
	defer this.lk.Unlock()
	for i := 0; i < len(this.wlst); i++ {
		if this.wlst[i] == w {
			this.wlst = append(this.wlst[:i], this.wlst[i+1:]...)
			return
		}
	}
}

func (this *MultiWriter) Write(p []byte) (n int, err error) {
	this.lk.RLock()
	defer this.lk.RUnlock()
	for _, w := range this.wlst {
		n, err = w.Write(p)
		if err != nil {
			return
		}
	}
	return
}
